// 模拟简单闭包

function whatWasTheLocal() {
    var captured = "Oh hai";
    return function() {
        return "The local was: " + captured;
    }
}

// 使用 whatWasTheLocal 函数
var reportLocal = whatWasTheLocal();
console.log(reportLocal()); // The local was: Oh hai

// 局部变量不是闭包唯一可以捕获的东西，函数的参数也可以捕获
function createScaleFunction(factor) {
    return function(v) {
        return _.map(v, function(n) {
            return (n * factor);
        });
    }
}

var scale10 = createScaleFunction(10);
console.log(scale10([1, 2, 3])); // [10, 20, 30]

// 
function makeAddr(captured) {
    return function(free) {
        return free + captured;
    }
}

var add10 = makeAddr(10);
console.log(add10(32)); // 42

var add1024 = makeAddr(1024);
console.log(add1024(11)); // 1035

// 捕获其他函数的高阶函数
function averageDamp(fun) {
    return function(n) {
        return average([n, fun(n)]);
    }
}

function average(array) {
    var sum = _.reduce(array, function(x, y) { return x + y });
    return sum / array.length;
}

var averageSq = averageDamp(function(n) { return n * n });
console.log(averageSq(10)); // 55